var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var conf = require('../tool/configTool');
const uploadDir = conf.sys.uploadDir;
fs.existsSync(uploadDir) || fs.mkdirSync(uploadDir);
console.log('upload dir =',uploadDir)

// var encoding = require('encoding');


/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });


// define a route music it creates readstream to the requested file and pipes the output to response

router.get('/home', function(req,res){

    return res.redirect('/views/fileHome.html');
});


router.get('/toUpload', function(req,res){

    return res.redirect('/views/fileUpload.html');
});


var multer  = require('multer');
var upload = multer({ dest: uploadDir });

var sd = require('silly-datetime');
router.post('/',upload.single('uploadFile'),function(req,res){

    var temp_path = req.file.path;
    var fileName = path.basename(req.file.originalname);

    var timeStap = sd.format(new Date(), 'YYYYMMDD_HHmmss');
    var target_path = path.join(uploadDir,timeStap+"_"+fileName);
    console.log("Uploading: " + fileName);
    fs.rename(temp_path, target_path, function(err,data) {

        if(err){
            res.json({
                code: -1,
                msg: 'upload file error'
            })
        }else{
            res.redirect(303,"/views/fileHome.html");
        }

    });

});

// var formidable = require('formidable');
// router.post('/',function(req,res){

//     console.log('开始文件上传....');
//     var form = new formidable.IncomingForm();
//     //设置编辑
//     // form.encoding = 'utf-8';
//     // //设置文件存储路径
//     // form.uploadDir = "../upload/";
//     //保留后缀
//     form.keepExtensions = true;
//     //设置单文件大小限制
//     // form.maxFieldsSize = 20000 * 1024 * 1024;
//     //form.maxFields = 1000;  设置所以文件的大小总和
//     // form.multiples = true;
//     form.parse(req, function(err, fields, files) {

//     	//console.log(fields);
//         //console.log(files.uploadFile.path);

//         var fileName = path.basename(files.uploadFile.name);
//         // files.userName.name;

//         // console.log('文件名:'+ fileName);

//         var t = (new Date()).getTime();
//         //生成随机数
//         var ran = parseInt(Math.random() * 8999 +10000);
//         //拿到扩展名
//         var extname = path.extname(fileName);

//         //path.normalize('./path//upload/data/../file/./123.jpg'); 规范格式文件名
//         // var oldpath =   path.normalize(files.thumbnail.path);
//         var oldpath = files.uploadFile.path;
//         //新的路径
//         let newfilename = t+ran+extname;
//         var newpath =  path.join(uploadDir,fileName);

//         // console.warn('oldpath:'+oldpath+' newpath:'+newpath);

//         fs.rename(oldpath,newpath,function(err){
//             if(err){
//                 res.json({
// 					code: -1,
// 					msg: 'upload error'
// 				});
//             }
//             // res.render('index', { title: '文件上传成功:', imginfo: newfilename });
// 			res.redirect('/views/fileHome.html');
//         })
//     });

// });

router.get('/', function(req,res){


    // var uploadDir = path.join(__dirname , '../','upload' );
    // var uploadDir = path.join(__dirname , '../','upload' );
    fs.exists(uploadDir,function(exists){
        if(exists)
        {
            var files = fs.readdirSync(uploadDir);//需要用到同步读取
            // files.forEach(function(file){
            //     console.log(file);
            // });

            res.json({code: 0,
                dat: files
            });
        }
        else
        {
            res.status(500).json({
                code:-1,
                msg:'路径不存在'
            })
        }

    });
});


// following is the code for downloading music files, note that the code remains same except that we add 2 headers viz
// Content-disposition and Content-Type which forces the chrome browser to force download rather than playing the media
// Note that the following is tested with google chrome and it may work differently in Mozilla and Opera based on your
// installed plugins.

router.get('/download', function(req,res){

    // console.log('***************',req.route)
    // console.log('***************',req.accepts())
    // console.log('***************',req.headers)
    var fileId = req.query.id;
    fileId = path.basename(fileId);
    // var file = path.join(__dirname , '../','upload' , fileId);
    var file = path.join(uploadDir , fileId);
    fs.exists(file,function(exists){
        if(exists)
        {

            // var fileName = encoding.convert(fileId,'ISO-8859-1','UTF-8');
            res.setHeader('Content-disposition', 'attachment; filename=' + new Date().getTime()+path.extname(fileId));
            // res.setHeader('Content-Type', 'application/audio/mpeg3')
            var rstream = fs.createReadStream(file);
            rstream.pipe(res);


            // res.set({
            //     'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
            //     'Content-Disposition': 'attachment; filename=' + fileName, //告诉浏览器这是一个需要下载的文件
            //     // 'Content-Length': stats.size  //文件大小
            // });
            // fs.createReadStream(filePath).pipe(res);

        }
        else
        {

            res.status(500).json({
                code: -1,
                msg: '文件不存在'
            });

        }
    });
});

module.exports = router;
